package com.situ.staff.controller;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import com.situ.staff.bean.User;
import com.situ.staff.service.UserService;

@Controller
@RequestMapping("/user")
public class UserController {
	@Autowired
	private UserService userService;

	@RequestMapping("/login")
	public String userLogin(User user, HttpSession session, Model model) {

		try {
			User loginUser = userService.login(user);

			session.setAttribute("user", loginUser);
			return "redirect:/";
		} catch (Exception e) {
			e.printStackTrace();
			model.addAttribute("error", e.getMessage());
			return "user/login";
		}

	}

	@RequestMapping("/reg")
	public String userReg(User user, Model model, String repassword) {

		try {
			userService.reg(user, repassword);
			return "user/login";
		} catch (Exception e) {
			e.printStackTrace();
			model.addAttribute("erreo", e.getMessage());
			return "user/reg";
		}
	}

	@GetMapping("/edit")
	public String edit() {

		return "user/edit";
	}

	@RequestMapping("/userEdit")
	public String userEdit(User user, String newpassword, String repassword, Model model, HttpSession session) {

		User loginUser = (User) session.getAttribute("user");
		if (loginUser == null) {
			return "user/login";
		}
		try {
			int edit = userService.edit(user, newpassword, repassword);
			if (edit > 0) {
				// 退出登录 重新登录
				return loginOut(session);
			} else {
				String error = null;
				if (edit == -1) {
					// 旧密码错误
					error = "旧密码错误";
				} else if (edit == -2) {
					error = "新旧密码不一致";
					// 7\新旧密码不一致
				} else {

				}
				model.addAttribute("error", error);
				return "user/edit";
			}
		} catch (Exception e) {
			e.printStackTrace();
			model.addAttribute("error", e.getMessage());
			return "user/edit";
		}
	}

	@RequestMapping("/loginout")
	public String loginOut(HttpSession session) {

		session.removeAttribute("user");
		// 清除session
		session.invalidate();

		return "user/login";
	}

	@GetMapping("/indext")
	public String indext() {

		return "redirect:/";
	}

}
